<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/8/21
 * Time: 下午1:38
 */

namespace Bpm\Controllers;

use Admin\Models\bpm\XHBpmNode;
use Admin\Models\bpm\XHBpmTemplate;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Helpers\Assets;
use Helpers\Controller;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Helpers\XhException;
use Modules\Coop;
use Modules\Power;
use Modules\School;

class TemplateController extends BpmNewBase
{


    public static $tag = ['workOrder' => '工单', 'processPlan' => '流程计划' ,'itemImpl' => '项目实施' ];

    public static $enum = [
        'iType' => [ 1 => '通用', 2 => '个人', 3 =>  '部门'],
    ];

    public static $config = [  //配置项 二级以上  是否可重复
        'workOrder'   => ['bMultiLevel' => 0, 'bRepeated' => true ],
        'processPlan' => ['bMultiLevel' => 0, 'bRepeated' => false ],
        'itemImpl'    => ['bMultiLevel' => 1, 'bRepeated' => true ]
    ];

    public function notFoundAction()
    {
        return $this->response->setStatusCode(404)->setJsonContent(['code' => 404, 'error' => 'page not found!']);
    }


//    public function ajaxForLevelAction()
//    {
//        try {
//            $flag = $this->request->getPost('flag', 'string');
//
//
//        } catch (\Exception $e) {
//            return $this->sendErrorResponse(
//                500,
//                $e->getMessage(),
//                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
//            );
//        }
//    }

    /**
     * 模板列表
     *
     * @return string
     *
     * modify by dale 20180324
     */
    public function tempListAction()
    {
        if (!Power::exist('Bpm_Template')) {
            return $this->sendViewError('没有权限');
        }
        Assets::easyUI();
        $this->view->pick('template/tempList');
        Assets::importJs('js/template/newTP.js');
        $listButtonArr = [];
        if (Power::exist('Bpm_Template_Add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if (Power::exist('Bpm_Template_Edit')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_upload', 'text' => '更新流程计划',
                'icon' => 'fa-pencil');

        }
        if (Power::exist('Bpm_Template_Del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
            'icon' => 'fa-search', 'style' => 'margin-left:10px');
        return $this->view->setVars([
            'List'       => Template::createList('list', 'templateList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'power'      => ['tempEdit' => Power::exist('Bpm_Template_Edit'),
                             'planEdit' => Power::exist('Bpm_Plan_Edit')  ]
        ]);
    }



    /**
     * 获取模板数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * modify by dale 20180324
     */
    public function getTempAction()
    {
        try {
            if (!UserPower::checkUserPower('Bpm_Template')) {
                return $this->sendErrorResponse(400, '没有权限');
            }
            $key = $this->request->getPost('key', 'string');
            $openId = $this->request->getPost('openId', 'int');
            $firstOpen = $this->request->getPost('firstOpen', 'int', null);
            $builder = $this->modelsManager->createBuilder()
                ->from('Admin\\Models\\bpm\\XHBpmTemplate')
                ->where('bDelete = 0');
            $userIds[] = Main::getLoginUserInfo('userId');
            if (!User::isAdmin()) {
                $depArr = Power::getExtraPower('dep', 'bpmTemplate');
                if ($depArr) {
                    $userIds = array_merge(Hrm::getUserByDepId($depArr, true), $userIds);
                }
                $builder->andWhere('iCreateUserId in ({ids:array})', ['ids' => $userIds]);
            }
            if ($key) {
                $builder->andWhere('sTPName like :key:', ['key' => '%'.$key.'%']);
            }
            $data = Main::runBuilderPage($builder, [
                'iType' => self::$enum['iType'] + [0 => ''],
            ]);
            $ids = array_column($data['rows'], 'iTPId');
            if (!$ids) {
                return $this->sendJsonResponse(['rows' => [], 'total' => 0]);
            }
            $nodes = XHBpmNode::find([
                'conditions' => "bDelete= 0 and iTPId in ({ids:array}) ",
                'bind'   => ['ids' => $ids ],
                'order'  => 'iSort,iNodeId,iTPId'
            ])->toArray();
            $newNodes = [];
            foreach ($nodes as $node) {
                $newNodes[$node['iTPId']][] = $node;
            }
            $tag = self::$tag;
            $openNodeArr = [];
            if ($openId) {
                $openNodeArr = $this->getParentNode($openId, $openNodeArr);
                $firstOpen = end($openNodeArr);
                $openNodeArr = array_reverse($openNodeArr);
                unset($openNodeArr[0]);
                $openNodeArr = array_values($openNodeArr);
            }
            foreach ($data['rows'] as $index => &$row) {
                $row['keyId'] = $row['iTPId'];
                $row['name']  = $row['sTPName'];
                $row['level'] = $row['bMultiLevel'] ? 'n' : 2;
                $row['tag']   = isset($tag[$row['sTag']]) ? $tag[$row['sTag']] : '';

                $child = Tool::getValue($newNodes, $row['iTPId'], null);
                if ($child) {
                    $row['children'] = $this->runNode($child, $row, $row['bMultiLevel'], $openNodeArr);
                    $row['state'] = 'closed';
                    if ($firstOpen && $firstOpen == $row['iTPId']) {
                        $row['state'] = 'open';
                    }
                }
            }
            unset($row);

            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 获取父节点
     *
     * @param $nodeId
     * @param $arr
     *
     * @return mixed
     *
     * create by dale  20180917
     */
    public function getParentNode($nodeId, &$arr)
    {
        $node = XHBpmNode::findFirst([
            'columns' => 'iParentId,iNodeId,iTPId',
            'conditions' => 'bDelete = 0 and iNodeId = :iNodeId:',
            'bind' => ['iNodeId' => $nodeId]
        ]);
        $arr[] = $nodeId;
        if ($node) {
            if ($node->iParentId == 0) {
                $arr[] = $node->iTPId;
                return  $arr;
            } else {
//                $arr[]= $node->iParentId;
                return $this->getParentNode($node->iParentId, $arr);
            }
        }
    }

    /**
     * 获取子节点
     *
     * @param $child
     * @param $parent
     * @param $bMultiLevel
     * @param $openNodeArr
     *
     * @return array
     *
     * create by dale  20180820
     */
    public function runNode($child, $parent, $bMultiLevel, $openNodeArr = [])
    {
        $nodeArr = [];
        $depEnum = XhhrmDepart::getDepEnum();
        if (!$bMultiLevel) {
            foreach ($child as $item) {
                $newArr = [
                    'name'        => $item['sNodeName'],
                    'keyId'       => $parent['sTag'] . '_' . $item['iNodeId'],
                    'bMultiLevel' => $parent['bMultiLevel'],
                    'sTag'        => $parent['sTag'],
                    'iTPId'       => $item['iTPId'],
                    'sContent'    => $item['sContent'],
                    'mDesc'       => $item['mDesc']
                ];
                if ($parent['sTag'] == 'processPlan') {
                    $newArr['sExcuteDeps'] = $this->getDepNames($item['sExcuteDeps'], $depEnum);
                    $newArr['sRelatDeps'] = $this->getDepNames($item['sRelatDeps'], $depEnum);
                }
                $nodeArr[] = $newArr;
            }
        } else {
            $classifyArr = [];
            foreach ($child as $item) {
                $classifyArr[$item['iParentId']][] = $item;
            }
            foreach ($classifyArr[0] as $item) { //所有父节点
                $newArr = [
                    'name'        => $item['sNodeName'],
                    'keyId'       => $parent['sTag'] . '_' . $item['iNodeId'],
                    'bMultiLevel' => $parent['bMultiLevel'],
                    'sTag'        => $parent['sTag'],
                    'iTPId'       => $item['iTPId'],
                    'sContent'    => $item['sContent'],
                    'mDesc'       => $item['mDesc'],
                    'iTargetId'   => $item['iTargetId']
                ];
                $newChild = Tool::getValue($classifyArr, $item['iNodeId'], null); //获取是否存在子节点
                if ($newChild) {
                    $newArr['children'] = $this->recursiveNode($classifyArr, $parent, $item['iNodeId'], $openNodeArr); //子节点递归
                    $newArr['state'] = 'closed';
                    if ($openNodeArr && in_array($item['iNodeId'], $openNodeArr)) {
                        $newArr['state'] = 'open';
                    }
                }
                $nodeArr[] = $newArr;
            }
        }
        return $nodeArr;
    }

    /**
     * 递归子节点
     *
     * @param $classifyArr
     * @param $parent
     * @param $currentNode
     * @param $openNodeArr
     *
     * @return array
     *
     * create by dale  20180820
     */
    public function recursiveNode($classifyArr, $parent, $currentNode, $openNodeArr = [])
    {
        $nodeArr = [];
        foreach ($classifyArr[$currentNode] as $item) {
            $newArr = [
                'name'        => $item['sNodeName'],
                'keyId'       => $parent['sTag'] . '_' . $item['iNodeId'],
                'bMultiLevel' => $parent['bMultiLevel'],
                'sTag'        => $parent['sTag'],
                'iTPId'       => $item['iTPId'],
                'sContent'    => $item['sContent'],
                'mDesc'       => $item['mDesc']
            ];
            $newChild = Tool::getValue($classifyArr, $item['iNodeId'], null); //获取是否存在子节点
            if ($newChild) {
                $newArr['children'] = $this->recursiveNode($classifyArr, $parent, $item['iNodeId'], $openNodeArr); //子节点递归
                $newArr['state'] = 'closed';
                if ($openNodeArr && in_array($item['iNodeId'], $openNodeArr)) {
                    $newArr['state'] = 'open';
                }
            }
            $nodeArr[] = $newArr;
        }
        return $nodeArr;
    }


    /**
     * 获取部门名称
     *
     * @param $ids
     * @param $depEnum
     * @return array|string
     *
     * modify by dale 20180324
     */
    public function getDepNames($ids, $depEnum)
    {
        if ($ids == '') {
            return '';
        }
        $ids = explode(',', $ids);
        if (!$ids) {
            return '';
        }
        $names = [];
        foreach ($ids as $id) {
            $names[] = $depEnum[$id];
        }
        $names = implode(',', $names);
        return $names;
    }

    /**
     * 模板表单
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20180820
     */
    public function tempFormAction()
    {
        $iTPId = $this->request->getQuery('iTPId', 'string');
        $this->view->pick('template/tempForm');
        if (!$iTPId) {
            if (!Power::exist('Bpm_Template_Add')) {
                return $this->sendViewError('没有权限');
            }
        } else {
            if (!Power::exist('Bpm_Template_Edit')) {
                return $this->sendViewError('没有权限');
            }
        }
        Assets::easyUI();
        Assets::importJs('js/template/tempForm.js');
        return $this->view->setVars([
            'sTag' => self::$tag,
            'iType' => self::$enum['iType']
        ]);
    }

    /**
     * 节点表
     *
     * @return bool|\Phalcon\Mvc\View|string
     *
     * modify by dale 20180324
     */
    public function nodeFormAction()
    {
        $iTPId = $this->request->getQuery('iTPId', 'int');
        $iNode = $this->request->getQuery('iNodeId', 'int');
        if (!$iTPId) {
            return $this->sendViewError('缺少参数');
        }
        if (!Power::exist('Bpm_Template_Edit')) {
            return $this->sendViewError('没有权限');
        }

        $template = XHBpmTemplate::findFirst($iTPId)->toArray();
        $tag = $template['sTag'];
        $this->view->setVar('templateType', self::$tag[$tag]);
        $this->view->setVar('iTPId', $template['iTPId']);
        if ($tag == 'processPlan') {
            $this->view->pick('template/nodeForm');
            Assets::easyUI();
            Assets::importJs('js/template/nodeForm.js');
        } elseif (in_array($tag, ['workOrder'])) {
            $this->view->pick('template/workOrder');
            Assets::importJs('js/template/workOrder.js');
        } elseif ($tag == 'itemImpl') {
            $parentId = $this->request->getQuery('iParentId', 'int');
            $this->view->pick('template/operatePro');
            Assets::importJs('js/template/operatePro.js');
            if (!$iNode) {
                $type = !$parentId ? 1 : 2;
                $this->view->setVars(['type' => $type]);
            }
        } else {
            return $this->sendViewError('未知模板类型');
        }
        if ($iNode) {
            $node = XHBpmNode::findFirst([
                'conditions' => "bDelete=:bDelete: AND iNodeId =:iNodeId: ",
                'bind' => array('iNodeId' => $iNode, 'bDelete' => 0),
            ])->toArray();
            if ($tag == 'itemImpl') {
                $type = $node['iParentId'] == 0 ? 1 : 2;
                $this->view->setVars(['type' => $type]);
            }
            return $this->view->setVars([
                'nodeData' => json_encode($node),
            ]);
        }
        return true;
    }


    /**
     * 保存模板
     *
     * @return string
     *
     * create by dale 20180324
     */
    public function saveTempAction()
    {
        try {
            $iTPId = $this->request->getPost('iTPId', 'string', null);
            if ($iTPId) {
                if (!UserPower::checkUserPower('Bpm_Template_Edit')) {
                    return $this->sendErrorResponse(403, '缺少权限');
                }
                $obj = XHBpmTemplate::findFirst($iTPId);
            } else {
                if (!UserPower::checkUserPower('Bpm_Template_Add')) {
                    return $this->sendErrorResponse(403, '缺少权限');
                }
                $obj = new XHBpmTemplate();
            }
            $tag = $this->request->getPost('sTag', 'string');
            if (!$tag) {
                return $this->sendErrorResponse(400, '模板类型必选');
            }
            $obj->assign($this->request->getPost());
            $obj->bMultiLevel = self::$config[$tag]['bMultiLevel'];

            if (!self::$config[$tag]['bRepeated']) {
                $temp = XHBpmTemplate::find([
                    'columns'    => 'iTPId,sTag',
                    'conditions' => 'bDelete = 0 and sTag = :sTag:',
                    'bind'       => ['sTag' => $tag],
                ])->toArray();
                if (!$iTPId && count($temp) > 0) {
                    return $this->sendErrorResponse(500, '该类型模板不允许重复创建');
                }
                if (count($temp) >= 2 ||
                    (count($temp) == 1 && $iTPId != null && $temp['iTPId'] != $iTPId ) ) {
                        return $this->sendErrorResponse(500, '该类型模板不允许重复创建');
                }
            }
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '失败');
            }
//            $this->createCommitLog('成功');
//            return $this->response->setJsonContent(['code' => 200, 'msg' => '成功！',
//                'id' => $temp->iTPId], JSON_UNESCAPED_UNICODE);
            return $this->sendSuccessResponse('成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 保存节点
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180324
     */
    public function saveNodeAction()
    {
        $iNodeId = $this->request->getPost('iNodeId', 'string');
        if (!Power::exist('Bpm_Template_Edit')) {
            return $this->sendErrorResponse(400, '缺少权限');
        }
        if ($iNodeId) {
            $obj = XHBpmNode::findFirst($iNodeId);
        } else {
            $obj = new XHBpmNode();
        }
        $obj->assign($this->request->getPost());
        $result = $obj->save();
        if ($result) {
            if (!$iNodeId) {
                $newObj = XHBpmNode::findFirst($obj->iNodeId);
                $newObj->iSort = $obj->iNodeId;
                if (!$newObj->save()) {
                    return $this->sendErrorResponse(400, '保存失败');
                }
            }
            return $this->sendSuccessResponse('保存成功');
        } else {
            return $this->sendErrorResponse(400, '保存失败');
        }
    }

    /**
     * 获取模板信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * modify by dale 20180324
     */
    public function getTempInfoAction()
    {
        if (!UserPower::checkUserPower('Bpm_Template')) {
            return $this->sendErrorResponse(400, '缺少权限');
        }
        $iTPId = $this->request->getPost('id');
        $obj = XHBpmTemplate::findFirst([
            'conditions' => "bDelete=:bDelete: AND iTPId =:iTPId: ",
            'bind' => array('iTPId' => $iTPId , 'bDelete' => 0),
        ]);

        return $this->sendJsonResponse($obj->toArray());
    }

    /**
     * 获取节点信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * modify by dale 20180324
     */
    public function getNodeInfoAction()
    {
        if (Power::exist('Bpm_Template')) {
            return $this->sendErrorResponse(400, '缺少权限');
        };

        $iNodeId = $this->request->getPost('id');
        $obj = XHBpmNode::findFirst([
            'conditions' => "bDelete=:bDelete: AND iNodeId =:iNodeId: ",
            'bind' => array('iNodeId' => $iNodeId , 'bDelete' => 0),
        ]);
        $data = $obj->toArray();
        $newobj = XHBpmTemplate::findFirst([
            'columns' => 'sTPName',
            'conditions' => "bDelete=:bDelete: AND iTPId =:iTPId: ",
            'bind' => array('iTPId' => $data['iTPId'] , 'bDelete' => 0),
        ]);
        $data['sTPName'] = $newobj->sTPName;

        return $this->sendJsonResponse($data);
    }


    public function delNodeAction()
    {
        try {
            $this->db->begin();
            if (!Power::exist('Bpm_Template_Del')) {
                return $this->sendErrorResponse(400, '没有权限');
            }
            $iNodeId = $this->request->getPost('id', 'string');
            if (!$iNodeId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj    = XHBpmNode::findFirst($iNodeId);
            if (!$obj) {
                return $this->sendErrorResponse(500, '找不到节点');
            }
            if (!$obj->delete()) {
                $this->db->rollback();
                return $this->sendErrorResponse('节点删除失败');
            }
            $this->recursiveDelNode($iNodeId); //递归删除子节点
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 删除子节点
     * @param $currentNodeId
     *
     * @return bool
     * @throws \Exception
     *
     * create by dale  20180821
     */
    public function recursiveDelNode($currentNodeId)
    {
        if (!$currentNodeId) {
            throw new \Exception('没有传入当前节点的id');
        }
        $nodes = XHBpmNode::find([
            'conditions' => 'bDelete = 0 and iParentId = :iParentId:',
            'bind'       => ['iParentId' => $currentNodeId]
        ]);
        if (!$nodes->toArray()) {
            return true;
        }
        foreach ($nodes as $node) {
            if (!$node->delete()) {
                throw new \Exception('子节点删除失败');
            }
            $this->recursiveDelNode($node->iNodeId);
        }
        return true;
    }



    /**
     * 删除模板
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20180821
     * modify by dale 20180821   删除列表
     */
    public function delTempAction()
    {
        try {
            $this->db->begin();
            if (!Power::exist('Bpm_Template_Del')) {
                return $this->sendErrorResponse(400, '没有权限');
            }
            $iTPId = $this->request->getPost('id', 'int');
            if (!$iTPId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XHBpmTemplate::findFirst($iTPId);
            if (!$obj) {
                return $this->sendErrorResponse(500, '找不到模板');
            }
            if (!$obj->delete()) {
                $this->db->rollback();
                return $this->sendErrorResponse('删除失败');
            }
            $nodes = XHBpmNode::find([
                'conditions' => 'bDelete = 0 and iTPId = :iTPId: ',
                'bind'       => ['iTPId' => $iTPId]
            ]);
            foreach ($nodes as $node) {
                if (!$node->delete()) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '节点删除失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }
    /**
     * 获取部门信息  id ,text easyui
     * @return string
     * created by dale 2017/8/16
     */
    public function getDepEnumAction()
    {
        return json_encode($this->recursionForArray2(0));
    }






    /**
     * 获取部门人员信息
     */
    public function getDepStaffEnumAction()
    {
        $this->view->disable();
        $deps = XhhrmDepart::find([
            'columns' => 'iDepId,sDepName',
            'conditions' => 'bDelete=0 AND iParentId=:iParentId:',
            'bind' => array('iParentId' => 0),
        ]);


        $ids = [];
        foreach ($deps as $dep) {
            $id = [];
            $id['id'] = $dep->iDepId;
            $id['text'] = $dep->sDepName;
            $ids[] = $id;
        }
        $array = [];
        foreach ($ids as $id) {
            $item = [];
            $item['id'] = 'D-' . $id['id'];
            $item['text'] = $id['text'];
            $item['iconCls'] = 'fa fa-group';
            $staffs = XhhrmStaff::find([
                'columns' => 'iStaffId,sStaffName,iUserId',
                'conditions' => "bDelete=0 AND sDepIds like :id:",
                'bind' => array("id" => '%,' . $id['id'] . ',%')
            ]);
            $staffs = $staffs->toArray();
            if ($staffs != null) {
                $childrens = [];
                foreach ($staffs as $staff) {
                    $child = [];
                    $child['id'] = $staff['iUserId'];
                    $child['iconCls'] = 'fa fa-user';
                    $child['text'] = $staff['sStaffName'];
                    $childrens[] = $child;
                }
                $item['children'] = $childrens;
                $item['state']    = "closed";
            }
            $array[] = $item;
        }
        return json_encode($array);
    }


    public function getDepStaffAction($id)
    {
        return json_encode($this->recursion($id));
    }


    public function recursion($parentId)
    {
        $parameters = array(
            'conditions' => "bDelete=:bDelete: AND iParentId=:parentId: ",
            'bind' => array('parentId' => $parentId, 'bDelete' => 0),
        );
        $objs = XhhrmDepart::find($parameters);  //当前传入部门id 为父部门的子部门
        if ($objs->toArray() == []) { //如果子部门为空,没有子部门
            $staffs = XhhrmStaff::find([
                'columns'    => 'iUserId,sStaffName,sDepIds',
                'conditions' => 'bDelete=0 AND sDepIds like :key: AND iStaffStatus = 1',
                'bind'       => ['key' => '%,' . $parentId . ',%'],
            ]);
            $staffs   = $staffs->toArray();
            $staffArr = [];
            foreach ($staffs as $staff) {
                $item            = [];
                $item['id']      = $staff['iUserId'];
                $item['text']    = $staff['sStaffName'];
                $item['iconCls'] = 'fa fa-user';
                $staffArr[]      = $item;
            }
            return $staffArr;
        }

        $array        = $objs->toArray(); //子部门
        $newArray     = [];
        $conditionArr = [];
        foreach ($array as $key => $value) {
            $newArray[$key]['id']       = 'D-' . $value['iDepId'];
            $newArray[$key]['text']     = $value['sDepName'];
            $newArray[$key]['iconCls']  = 'fa fa-group';
            $newArray[$key]['children'] = $this->recursion($value['iDepId']);
            if ($newArray[$key]['children']) {
                $newArray[$key]['state'] = "closed";
            }
            $conditionArr[] = "sDepIds not like '%," . $value['iDepId'] . ",%' ";
        }
        $conditionArr = implode(' AND ', $conditionArr);
        $conditionArr = '( ' . $conditionArr . ' )';

        $staffs = XhhrmStaff::find([
            'columns'    => 'iUserId,sStaffName,sDepIds',
            'conditions' => "bDelete=0 AND sDepIds like :key: AND iStaffStatus = 1  AND  " . $conditionArr,
            'bind'       => ['key' => '%,' . $parentId . ',%'],
        ])->toArray();
        if ($staffs != []) {
            foreach ($staffs as $staff) {
                $item            = [];
                $item['id']      = $staff['iUserId'];
                $item['text']    = $staff['sStaffName'];
                $item['iconCls'] = 'fa fa-user';
                $newArray[]      = $item;
            }
        }
        return $newArray;
    }

    public function recursionForArray2($parentId)
    {
        $parameters = array(
            'conditions' => "bDelete=:bDelete: AND iParentId=:parentId: ",
            'bind'       => array('parentId' => $parentId, 'bDelete' => 0),
        );
        $objs       = XhhrmDepart::find($parameters);
        if ($objs == null) {
            return [];
        }
        $array    = $objs->toArray();
        $newArray = [];
        foreach ($array as $key => $value) {
            $newArray[$key]['id']       = $value['iDepId'];
            $newArray[$key]['text']     = $value['sDepName'];
            $newArray[$key]['iconCls']  = 'fa fa-group';
            $newArray[$key]['children'] = $this->recursionForArray2($value['iDepId']);
            if ($newArray[$key]['children']) {
                $newArray[$key]['state'] = "closed";
            }
        }
        return $newArray;
    }

    public function getNodeDescAction()
    {
        $sNodeName = $this->request->getPost('sNodeName');
        $obj       = XHBpmNode::findFirst([
            'conditions' => 'bDelete=0 AND sNodeName=:sNodeName:',
            'bind'       => ['sNodeName' => $sNodeName]
        ]);
        if (!$obj) {
            return $this->sendErrorResponse(500, '找不到' . $sNodeName . '节点');
        }
        return $this->sendJsonResponse(['desc' => $obj->mDesc]);
    }


    public function moveTemplateAction()
    {
        try {
            $nodeName = '新上项目实施标准';
            $temp = XHBpmTemplate::findFirst([
                'conditions' => 'bDelete = 0 and sTPName = :sTPName:',
                'bind'       => ['sTPName' => $nodeName]
            ]);
            $nodeArr = XHBpmNode::find([
                'columns'    => 'iNodeId,sNodeName,iTPId,iParentId,iSort,sContent,mDesc',
                'conditions' => 'bDelete = 0 and iTPId = :iTPId:',
                'bind'       => ['iTPId' => $temp->iTPId],
                'order'      => 'iTPId,iParentId'
            ])->toArray();
            $this->db->begin();
            $firstTempArr = [];
            foreach ($nodeArr as $index => $row) {
                if ($row['iParentId'] == 0) {
                    $firstTempArr[] = $row;
                }
            }
            $copyNodeArr = [];
            foreach ($nodeArr as $index => $row) {
                if ($row['iParentId'] != 0) {
                    $copyNodeArr[$row['iParentId']][] = $row;
                }
            }
//            var_dump($copyNodeArr);die;
//            var_dump($firstTempArr);die;
            if ($firstTempArr) {
                foreach ($firstTempArr as $row) {
                    $temp = new XHBpmTemplate();
                    $temp->bMultiLevel = 1;
                    $temp->sTPName = $row['sNodeName'];
                    $temp->sTag = 'itemImpl';
                    if (!$temp->save()) {
                        throw new XhException('父节点转移失败');
                    }
                    if (isset($copyNodeArr[$row['iNodeId']])) {
                        $firstNodeArr = $copyNodeArr[$row['iNodeId']];
                        if ($firstNodeArr) {
                            foreach ($firstNodeArr as $firstNode) {
                                $node = new XHBpmNode();
                                $node->sNodeName = $firstNode['sNodeName'];
                                $node->iTPId = $temp->iTPId;
                                $node->iSort = $firstNode['iSort'];
                                $node->sContent = $firstNode['sContent'];
                                $node->mDesc = $firstNode['mDesc'];
                                $node->iParentId = 0;
                                if (!$node->save()) {
                                    throw new XhException('节点保存失败');
                                }
                                $this->runNodeInsert($copyNodeArr, $firstNode, $node->toArray());
                            }
                        }

                    }
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('转移成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 递归插入数据
     *
     * @param $allNodeArr
     * @param $parentNode
     * @param $nowNode
     *
     * @return bool
     * @throws XhException
     *
     * create by dale  20180912
     */
    public function runNodeInsert($allNodeArr, $parentNode, $nowNode)
    {
        if (!isset($allNodeArr[$parentNode['iNodeId']])) {
            return true;
        }
        $matchArr = $allNodeArr[$parentNode['iNodeId']];
        foreach ($matchArr as $matchNode) {
            $node = new XHBpmNode();
            $node->sNodeName = $matchNode['sNodeName'];
            $node->iTPId = $nowNode['iTPId'];
            $node->iParentId = $nowNode['iNodeId'];
            $node->iSort = $matchNode['iSort'];
            $node->sContent = $matchNode['sContent'];
            $node->mDesc = $matchNode['mDesc'];
            if (!$node->save()) {
                throw new XhException('节点保存失败');
            }
            $this->runNodeInsert($allNodeArr, $matchNode, $node->toArray());
        }
        return true;
    }

//    public function testAction(){
//        var_dump(Coop::getProduce([9, 12], true));
//    }

}